package com.study.spmongodb.studymogo.dao;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.study.spmongodb.studymogo.pojo.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author study
 * @version 1.0
 * @date 2020/10/7 19:00
 */
@Component
public class PersonDao {
    @Autowired
    private MongoTemplate mongoTemplate;

    public void save(Person person) {
        this.mongoTemplate.save(person);
    }

    public List<Person> queryByName(String name) {
        final Query query = Query.query(Criteria.where("name").is(name));
        return this.mongoTemplate.find(query, Person.class);
    }

    /**
     * 分页
     *
     * @param page 页码
     * @param rows 每页数量
     * @return 分页查询后的数量
     */
    public List<Person> queryPage(Integer page, Integer rows) {
        final Query query = new Query().limit(rows).skip((page - 1) * rows);
        return this.mongoTemplate.find(query, Person.class);
    }

    /**
     * 更新一条数据
     *
     * @param person 更新的值
     * @return UpdateResult
     */
    public UpdateResult update(Person person) {
        Query query = Query.query(Criteria.where("id").is(person.getId()));
        final Update update = Update.update("age", person.getAge());
        return this.mongoTemplate.updateFirst(query, update, Person.class);
    }

    /**
     * 删除
     *
     * @param id 删除ID
     * @return DeleteResult
     */
    public DeleteResult del(String id) {
        Query query = Query.query(Criteria.where("id").is(id));
        return this.mongoTemplate.remove(query, Person.class);
    }

    public List<Person> queryPage2(Integer page, Integer rows) {
        PageRequest pageRequest = PageRequest.of(page - 1, rows);
        //设置查询条件 并 分页
        Query query = new Query();
        System.out.println(query);
        final List<Person> people = this.mongoTemplate.find(query, Person.class);

        query.with(pageRequest);
        final List<Person> people1 = this.mongoTemplate.find(query, Person.class);
        System.out.println(people1);
        return people;
    }

}
